<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/9
 * Time: 10:26
 */

namespace app\api\controller;


use addons\cms\model\Channel;
use addons\cms\model\Page;
use app\admin\model\cms\Archives;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\ArchiveCollect;
use think\Db;
use think\Exception;
use think\Request;

class Article extends Api
{
    protected $noNeedLogin = ['*'];

    protected $noNeedRight = ['*'];

    public function index(Request $request)
    {
        try {
            $category_id = $request->request('category_id');
            $list = Db::table('fa_cms_archives')->alias('a')
                ->join('fa_cms_addonnews n', 'a.id = n.id')
                ->where(['a.channel_id' => $category_id, 'deletetime' => NULL])
                ->order('a.createtime desc')
                ->field('a.id,a.title,a.description,a.image,a.createtime,a.publishtime,n.source,n.content')
                ->paginate()
                ->toArray();
            if (!empty($list)) {
                foreach ($list['data'] as $key => $item) {
                    if (strpos($item['image'], '://')) {
                        $list['data'][$key]['image'] = $item['image'];
                    } else {
                        if (!empty($item['image'])) {
                            $url = config('app_url') . $item['image'];
                        } else {
                            $url = '';
                        }
                        $list['data'][$key]['image'] = $url;
                    }
                }
            }
            $this->success('', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    public function hot_list()
    {
        try {
            $list = Channel::where(['parent_id' => 1])
                ->select();
            $category = [];
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    $category[$key]['category_id'] = $value['id'];
                    $category[$key]['category_name'] = $value['name'];
                    $list = Archives::where(['channel_id' => $value['id']])
                        ->order('createtime', 'desc')
                        ->limit(3)
                        ->field('id,title,description,image,createtime,publishtime,source')
                        ->paginate();
                    $category[$key]['articles'] = $list;
                }
            }
            $future = \app\common\library\FutureService::getInstance()->getComrms('USDCNH,SH000001,SHFEAU,CMEJY');
            $this->success('', ['categories' => $category, 'banners' => ['assets/img/b1@3x.png', 'assets/img/b2@3x.png'], 'futures' => $future->Obj]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 分类
     */
    public function channel()
    {
        try {
            $list = Channel::where(['parent_id' => 1])
                ->order('weigh desc')
                ->select();
            $data = [];
            foreach ($list as $key => $item) {
                $data[$key]['id'] = $item['id'];
                $data[$key]['name'] = $item['name'];
            }
            $this->success('', $data);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 判断用户是否收藏该新闻
     */
    public function is_collect(Request $request)
    {
        try {
            $aid = $request->param('aid');
            $archive = \addons\cms\model\Archives::find($aid);
            if (empty($aid) || empty($archive))
            {
                throw new exception('Not find');
            }
            if ($this->auth->id == '')
            {
                throw new exception('You need to Login');
            }
            $exists = ArchiveCollect::where(['aid' => $aid, 'user_id' => $this->auth->id])->find();
            $data['collect_status'] = 0;
            if ($exists)
            {
                $data['collect_status'] = 1;
            }
            $this->success('', $data);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 收藏
     */
    public function collect(Request $request)
    {
        try {
            $aid = $request->param('aid');
            $archive = \addons\cms\model\Archives::find($aid);
            if (empty($aid) || empty($archive))
            {
                throw new exception('Not find');
            }
            $exists = ArchiveCollect::where(['aid' => $aid, 'user_id' => $this->auth->id])->find();
            if ($exists)
            {
                throw new exception('Has been collected');
            }
            ArchiveCollect::create([
                'user_id'       => $this->auth->id,
                'aid'    => $aid,
                'created_at'    => time(),
            ]);
            $this->success();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 取消收藏
     */
    public function uncollect(Request $request)
    {
        try {
            $aid = $request->param('aid');
            $archive = \addons\cms\model\Archives::find($aid);
            if (empty($aid) || empty($archive))
            {
                throw new Exception("Not find");
            }
            $exists = ArchiveCollect::where(['aid' => $aid, 'user_id' => $this->auth->id])->find();
            if (empty($exists))
            {
                throw new Exception("You haven't collected");
            }
            $exists->delete();

            $this->success();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 评论
     */
    public function comment(Request $request)
    {
        try {
            $params = $request->param();
            $request->filter('strip_tags');
            $useragent = $request->server('HTTP_USER_AGENT', '');
            $ip = $request->ip();
            $auth = Auth::instance();


            if (!$auth->id)
            {
                throw new Exception("You need to Login");
            }
            if (!isset($params['aid']) || !isset($params['content']))
            {
                throw new Exception("Contents not null");
            }
            $params['type'] = isset($params['type']) ? $params['type'] : 'archives';
            $archives = $params['type'] == 'archives' ? \addons\cms\model\Archives::get($params['aid']) : Page::get($params['aid']);
            if (!$archives || $archives['status'] == 'hidden')
            {
                throw new Exception("Not find");
            }
            $params['user_id'] = $auth->id;
            $params['content'] = nl2br($params['content']);
            $params['ip'] = $ip;
            $params['useragent'] = $useragent;
            $params['status'] = 'normal';
            $ret = \addons\cms\model\Comment::create($params);
            if (empty($ret))
            {
                throw new Exception("Comment fail");
            }
            $this->success();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取新闻评论列表
     */
    public function comment_list(Request $request)
    {
        try {
            $aid = $request->request('aid');
            if (empty($aid))
            {
                throw new Exception("invaild parameter");
            }
            $list = \addons\cms\model\Comment::alias('c')
                ->join('fa_user u', 'c.user_id = u.id')
                ->field('c.content, c.createtime, u.nickname, u.avatar')
                ->where(['c.aid' => $aid])
                ->order('c.createtime desc')
                ->paginate();
            $this->success('', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }



}